package cn.cloud.all.security.core.userdetails.memory;

import java.beans.PropertyEditorSupport;
import java.util.ArrayList;
import java.util.List;

import org.springframework.util.StringUtils;

public class UserAttributeEditor extends PropertyEditorSupport {

    public void setAsText(String s) throws IllegalArgumentException {
        if (StringUtils.hasText(s)) {
            String[] tokens = StringUtils.commaDelimitedListToStringArray(s);

            UserAttribute userAttrib = new UserAttribute();
            List<String> authoritiesAsStrings = new ArrayList<>();

            for (int i = 0; i < tokens.length; i++) {
                String currentToken = tokens[i].trim();
                if (i == 0) {
                    userAttrib.setPassword(currentToken);
                } else {
                    switch (currentToken.toLowerCase()) {
                        case "enabled":
                            userAttrib.setEnabled(true);
                            break;
                        case "disabled":
                            userAttrib.setEnabled(false);
                            break;
                        default:
                            authoritiesAsStrings.add(currentToken);
                            break;
                    }
                }
            }
            userAttrib.setAuthoritiesAsString(authoritiesAsStrings);
            if (userAttrib.isValid()) {
                setValue(userAttrib);
            } else {
                setValue(null);
            }
        } else {
            setValue(null);
        }
    }
}
